import React from "react"
import { Divider } from "@taroify/core"
import GpContainer from "@/components/GpContainer"
import { Navigator, Text, View } from "@tarojs/components"
import GpBlockTitle from "@/components/GpBlockTitle"
import GpQAItem from "@/components/GpQAItem"
import GpQAContentItem from "@/components/GpQAContentItem"
import GpInstitutionItemPure from "@/components/GpInstitutionItemPure"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import { getQADetail } from "@/apis/index"
import Taro from "@tarojs/taro"
import { commonUrls, makePagePath } from "@/utils/router"
import { pageMapper } from "@/constants/pageMap"
import { cloneDeep, setPageMeta } from "@/utils/common"
import styles from "./index.module.scss"
import clsx from "clsx"

const ports = [{ text: "问答详情" }]
type IDetail = {
  id: number
  title: string
  questioner: string
  content: string
  topicId: number
  topicName: string
  content__seo: string
  projects: string[]
  tags: string[]
}
type IState = {
  detail: IDetail | null
  answers: any[]
  /** 更多问答 */
  moreQAs: any[]
  /** 推荐机构 */
  agencys: any[]
}
type IData = {
  id: string
}
class TrainGuide extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      detail: null,
      answers: [],
      moreQAs: [],
      agencys: []
    }
    this.extData = {
      id: ""
    }
  }
  onShareAppMessage() {}
  onLoad(options: Recordable) {
    this.extData.id = options.id
    this.getDetail()
  }
  componentDidShow() {
    this.setPageInfo(this.state.detail)
  }
  setPageInfo = (detail: INullable<IDetail>) => {
    if (detail) {
      const keywords = [] as string[]
      const _projects = (detail.projects || []).slice(0, 2)
      const tag_1 = detail.tags ? detail.tags[0] : ""
      const tag_2 = detail.tags ? detail.tags[1] || tag_1 : ""
      if (_projects.length >= 2) {
        keywords.push(_projects[0].concat(tag_1))
        keywords.push(_projects[1].concat(tag_2))
      } else {
        keywords.push(_projects[0].concat(tag_1))
      }
      setPageMeta({
        keywords: keywords.join("，"),
        title: `${detail.title}-择艺宝`,
        description: detail.content__seo
      })
    }
  }
  getDetail = () => {
    Taro.showLoading()
    getQADetail(this.extData.id)
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const _moreQAs = retData.moreQAs || []
          _moreQAs.forEach(l => {
            l.url = makePagePath(pageMapper.qaDetail, { id: l.id })
          })
          const content__seo = (retData.introduce || "").substr(0, 80)
          const detail = {
            id: retData.id,
            title: retData.title,
            questioner: retData.questioner,
            content: retData.content,
            topicId: retData.topicId,
            topicName: retData.topicName,
            content__seo,
            projects: retData.projects,
            tags: retData.tags
          }
          this.setPageInfo(detail)
          this.setState({
            detail,
            answers: retData.answers || [],
            moreQAs: _moreQAs,
            agencys: retData.agencys || []
          })
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  handleSupport = (itemKey: any) => {
    const _answers = cloneDeep(this.state.answers)
    const finder = _answers.find(l => l.id === itemKey)
    if (finder) {
      finder.isLike = true
      finder.likes = finder.likes + 1
      this.setState({
        answers: _answers
      })
    }
  }
  renderContent = () => {
    const detail = this.state.detail!
    const { answers } = this.state
    const jumpLink = makePagePath(pageMapper.columnMain, { id: detail.topicId })
    const len = answers.length
    const colors = ["#ED8888", "#FFB70F", "#FE5900", "#5FCC8F", "#57C6D8", "#A6D4AE"]
    return (
      <View className="pt-45px pb-40px px-40px bg-hex-fff">
        <Text className="yahei-bold font-bold text-36px leading-64px text-hex-2c2c35">
          {detail.title}
        </Text>
        <View className="pt-42px">
          <GpQAContentItem
            avatar="#A6D4AE"
            content={detail.content}
            symbolText={detail.questioner}
          />
          <Divider className={styles["divider"]} />
        </View>
        {/* 回复 */}
        <View className="yahei-bold font-bold text-30px text-hex-2c2c35 mb-40px">
          回复({answers.length})
        </View>
        <View className="flex flex-col">
          {answers.map((l, index) => (
            <GpQAContentItem
              key={l.id}
              avatar={colors[index % colors.length]}
              content={l.answerContent}
              symbolText={l.answerUser}
              allowSupport
              supportCount={l.likes}
              supported={l.isLike}
              onSupport={this.handleSupport}
              itemKey={l.id}
              className={clsx({
                "mb-23px": index !== len - 1
              })}
            />
          ))}
        </View>
        {detail.topicName ? (
          <View className="yahei font-normal text-24px text-hex-666 mt-43px">
            *本文被收录于专题{">> "}
            <Navigator url={jumpLink} className="text-hex-1a8cff inline" hoverClass="none">
              《{detail.topicName}》
            </Navigator>
          </View>
        ) : null}
      </View>
    )
  }
  /** 更多问答 */
  renderMoreQA = () => {
    const { moreQAs } = this.state
    if (moreQAs.length <= 0) return null
    return (
      <View className="pt-32px bg-hex-fff mt-20px">
        <View className="pb-34px px-30px">
          <GpBlockTitle title="更多问答" />
        </View>
        <View className="px-30px pb-40px flex flex-col">
          {moreQAs.map(l => (
            <GpQAItem
              key={l.id}
              title={l.title}
              answer={l.answerUser}
              content={l.answerContent}
              navigationLink={l.url}
            />
          ))}
          {/* 查看更多 */}
          <Navigator
            hoverClass="none"
            url={commonUrls.examQA}
            className="block yahei font-normal text-26px text-hex-b8b8bf w-654px mx-auto mt-32px h-80px box-border leading-78px bg-hex-fff border border-solid border-hex-eee text-center rounded-36px"
          >
            查看更多 {">"}
          </Navigator>
        </View>
      </View>
    )
  }
  /** 推荐机构 */
  renderInstitution = () => {
    const { agencys } = this.state
    if (agencys.length <= 0) return null
    return (
      <View className="pt-32px bg-hex-fff mt-20px">
        <View className="pb-34px px-30px">
          <GpBlockTitle
            title="推荐机构"
            showArrow
            navigatorLink={commonUrls.institution}
            openType="switchTab"
          />
        </View>
        <View className="px-30px pb-40px flex flex-col">
          {agencys.map((l, index) => (
            <GpInstitutionItemPure key={index} institution={l} />
          ))}
        </View>
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  render(): React.ReactNode {
    if (!this.state.detail) return null
    return (
      <GpContainer>
        <View>
          {/* 问答内容 */}
          {this.renderContent()}
          {/* 更多问答 */}
          {this.renderMoreQA()}
          {/* 推荐机构 */}
          {this.renderInstitution()}
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar />
      </GpContainer>
    )
  }
}
export default TrainGuide
